package vn.demand.dragon.model
{
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.business.LoadTasksByReferenceDelegate;
	import vn.demand.dragon.model.business.SaveTasksDelegate;
	import vn.demand.utils.DpUtils;
	
	public class TaskProxy extends Proxy implements IProxy
	{
		public static const NAME:String = "TaskProxy";
		
		public var errorStatus:String;
		
		private var tasks:XMLListCollection;
		private var taskList:XMLList;
		
		public var projectVO:Object;
		
		public static var arr:Array = ['task_quotation', 'task_item', 'task_cargo_type', 'task_container', 'task_method', 'task_shipping_type', 'task_place_from', 'task_place_to', 'task_truck_detention', 'task_unit', 'task_condition'];
		
		public static function makeId(projectVO:Object):String {
        	return NAME + projectVO.project_id + "::";
        }
		
		private var userProxy:UserProxy = null;
		
		public function TaskProxy(proxyName:String, data:Object = null) 
        {
            super (proxyName, data );
            this.projectVO = data;
            userProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
        }
        
        public function reinit(projectVO:Object) {
        	this.data = projectVO;
        	this.projectVO = data;
        	taskList = new XMLList();
        	tasks = new XMLListCollection(taskList);
        }
        
        public function get quotationLinesProxy():QuotationLinesProxy {
        	return facade.retrieveProxy(QuotationLinesProxy.NAME) as QuotationLinesProxy;
        }
        
        public function get masterdataProxy():MasterdataProxy {
        	return facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
        }
        
        public function loadTaskByReference():void {
			var delegate:LoadTasksByReferenceDelegate = new LoadTasksByReferenceDelegate(resultLoadTaskByReference, failedLoadTaskByReference);
			delegate.loadTaskByReferenceService(projectVO.project_id);
		}
		
		public function resultLoadTaskByReference(rpcEvent:Object):void {
			taskList = rpcEvent.result.tasks.item;
			tasks = new XMLListCollection(rpcEvent.result.tasks.item);
			sendNotification(FFIAApplicationFacade.LOAD_TASKS_BY_REFERENCE_SUCCESS, proxyName, projectVO.project_id);
		}
		
		public function failedLoadTaskByReference(rpcEvent:Object):void {
			errorStatus = "Could not load quotation lines!";
			sendNotification(FFIAApplicationFacade.LOAD_TASKS_BY_REFERENCE_FAILED, errorStatus, projectVO.project_id);
		}
		
		public function get tasksDP():XMLListCollection {
			return tasks;
		}
		
		public function newTask():XML {
			var xml:XML = new XML("<item>" + 
					"<task_id>0</task_id>" + 
					"<task_project>" + projectVO.project_id  +   "</task_project>" +
					"<task_resource>" + userProxy.userInfo.user_id + "</task_resource>" + 
					"<task_division>" + userProxy.userInfo.div_id + "</task_division>" + 
					"<task_costcenter>" + userProxy.userInfo.cc_id + "</task_costcenter>" + 
					"</item>");
			RIALogger.debug(this, xml.toXMLString());
			return xml;
		}
		
		public function removeTask(selIndex:int):Object {
			return tasksDP.removeItemAt(selIndex);
		}
		
		public function copyTask(projectVO:Object, copyItem:Object, targetRow:int):Object {
			var item:XML = new XML(XML(copyItem).toXMLString());
			item['task_project'] = String(projectVO.project_id);
			item['task_id'] = '';
			item['task_is_complete'] = false;
			if (targetRow == tasksDP.length - 1) {
				tasksDP.addItemAt(item, targetRow);
			} else {
				tasksDP.setItemAt(item, targetRow);
			}
			return item;
		}
		
		public function saveTasks(projectVO:Object):void {
			for each(var sel in tasksDP) {
				RIALogger.debug(this, 'calSalesAmount for task: ' + sel.task_id);
				this.calTaskSaleAmount(sel);
				var selQuote:int = sel.task_quotation;
				var quoteVersion:String = quotationLinesProxy.getQuotationById(selQuote, 'quote_version');
				sel.task_quotation_version = quoteVersion;
				RIALogger.debug(this, "==>" + selQuote + " link task with quotation, quote_version = " + quoteVersion);
			}
			var xml:String = "<root>" + tasksDP.toXMLString() + "</root>";
			var delegate:SaveTasksDelegate = new SaveTasksDelegate(resultSaveTasks, faultSaveTasks);
			delegate.saveTasks(xml);
		}
		
		public function resultSaveTasks(rcpEvent:Object):void {
			var success:Boolean = rcpEvent.result.success == 'true'; 
			if (success) {
				sendNotification(FFIAApplicationFacade.TASK_UPDATED, projectVO, projectVO.project_id);
			} else {
				RIALogger.error(this, "Save quotation lines failed with error message: \n" + rcpEvent.result.messages);
				sendNotification(FFIAApplicationFacade.TASK_UPDATE_FAILED, String(rcpEvent.result.messages));
			}
		}
		
		public function faultSaveTasks(rcpEvent:Object):void {
			Alert.show('TaskProxy error: \n' + rcpEvent.fault);
			errorStatus = "Something wrong when save quotation lines!";
			sendNotification(FFIAApplicationFacade.TASK_UPDATE_FAILED, errorStatus, projectVO.project_id);
		}

		public function getVAT(task:Object):Number {
			var vatType:Number = quotationLinesProxy.getVATType(task);
			RIALogger.debug(this, 'vatType: ' + vatType);
			var item:Object = masterdataProxy.getItemById(task.task_item, true);
			RIALogger.debug(this, "" + item);
			if (vatType == 1) {
				return item.vat_code_value
			} else if (vatType == 2) {
				return -1 * item.vat_code_value;
			}
			return 0;
		}

		public function calTaskSaleAmount(task:Object):void {
			var tax:Number = getVAT(task);
			var matchPrice:Object = quotationLinesProxy.getMatchPrice(task);
			RIALogger.debug(this, "match price: " + matchPrice.isMatch + ", qitem_id"+ matchPrice.qitem_id + ", price"+ matchPrice.price + ", mode:"+ matchPrice.mode);
			RIALogger.debug(this, "vat tax: " + tax);
			if (matchPrice.isMatch == false) {
				sendNotification("");
				return;
			}
			
			task.task_vat = tax;
			var saleAmount:Number = 0;
			if (matchPrice.mode == 1) {//per shipment
				saleAmount = matchPrice.price;
			} else {//per quantity
				saleAmount = matchPrice.price * task.task_figure;
			}
			saleAmount += quotationLinesProxy.getSurcharge1Price(matchPrice.qitem_id, task);
			saleAmount += quotationLinesProxy.getSurcharge2Price(matchPrice.qitem_id, task);
			RIALogger.debug(this, "sale amount: " + saleAmount);
			if (tax > 0) {//including vat
				task.task_fee = saleAmount / ((100 + tax) / 100);
				task.task_vat_amount = saleAmount - task.task_fee;
			} else {//excluding vat
				task.task_fee = saleAmount;
				task.task_vat_amount = task.task_fee * -1 * tax / 100;
			}
			RIALogger.debug(this, "task fee: " + task.task_fee);
			RIALogger.debug(this, "task vat amount: " + task.task_vat_amount);
		}
		
		public function getTaskById(task_id:Number, suffix:Boolean=false):String {
			var list:XMLList = taskList.(Number(child('task_id')) == task_id);
			if (list.length() == 0) {
				return "";
			}
			var itemName:String = masterdataProxy.getItemById(list[0].task_item) as String;
			return suffix ? (itemName + " - " + list[0].task_description) : itemName;
		}
		
		public function isTaskComplete(itemIndex:int):Boolean {
			var sel:Object = tasksDP.getItemAt(itemIndex);
			return DpUtils.isTrue(sel.task_is_complete);
		}
	}
}